<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入部门名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.sn" placeholder="请输入部门编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="filters.state" placeholder="请选择" clearable>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="queryDepts">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd()">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="140" sortable>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="140"  sortable>
      </el-table-column>
      <el-table-column prop="state" label="是否启用" width="140" :formatter="formatSex" sortable>
        <template scope="scope">
          <div v-if="scope.row.state ==0" slot="reference">
            <el-tag size="medium" type="danger">禁用</el-tag>
          </div>
          <div v-if="scope.row.state ==1" slot="reference">
            <el-tag size="medium" type="success">启用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="管理员" width="140" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="140" sortable>
      </el-table-column>
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" @click="handlesave(scope.$index, scope.row,)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--保存页面-->
    <!--
        :visible.sync 控制模态框是否显示
        :rules="saveFormRules" 表单验证的绑定
        prop="sn" 专业用来做表单验证
    -->
    <el-dialog title="编辑" :title="saveTitle" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员">
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <!--
                v-for 循环
                :key  用于去重的  必须要唯一
                :label 显示选中的值
                :value 提交后给v-model的值
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent_id"
                       :options="tree"
                       :props="{
                          checkStrictly:true,
                          label:'name',
                          value:'id',
                       }"
             clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {

  data() {
    return {
      total: 0,
      currentPage:1,
      pageSize:10,


      depts: [],//列表数据

      filters: {
        keyword: '',
        sn: '',
        state: '',
      },
      //批量删除用的
      sels: [],//列表选中列

      //新增和修改用
      saveFormVisible: false,//编辑界面是否显示
      saveTitle:"",//设置标题  新增或者是编辑
      saveLoading: false,//忙等
      saveFormRules: {//表单的验证
        sn: [
            //必传            提示信息              失去焦点时触发
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],


      },
      //编辑界面数据 form表单
      saveForm: {
        id: null,
        sn: '',
        name:'',
        state: 0,
        manager_id: null,
        parent_id: null,
      },

      //忙等 默认关闭
      listLoading: false,




      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //新增界面数据
      addForm: {
        name: '',
        sex: -1,
        age: 0,
        birth: '',
        addr: ''
      }

    }
  },
  methods: {
    //当前页的事件
    handleCurrentChange(val) {//自动获取当前页码
      this.currentPage = val;
      this.getdepts();//刷新列表
    },
    //选择条数的事件
    handleSizeChange(val){//自动获取当前页的查询条数
      this.pageSize = val
      this.getdepts();//刷新列表
    },
    queryDepts(){
      this.currentPage = 1
      this.getdepts()
    },
    //获取部门列表
    getdepts() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword,
        sn: this.filters.sn,
        state: this.filters.state,
      };
      this.listLoading = true;//开启忙等
      //获取部门列表分页的数据
      this.$http.post("/dept/pagelist",para).then(res=>{
        this.depts = res.data.data
        this.total = res.data.total
        this.listLoading = false;//关闭忙等
      })
      //NProgress.start();
      // getdeptListPage(para).then((res) => {
      //   this.total = res.data.total;
      //   this.depts = res.data.depts;
      //   this.listLoading = false;
      //   //NProgress.done();
      // });
    },
    //获取员工列表
    getEmployee(){
      this.$http.get("/emp/list").then(res=>{
        this.employees = res.data
      })
    },
    //获取部门树
    getTree(){
      this.$http.get("/dept/tree").then(res=>{
        this.tree = res.data
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {//确定要做的事
        this.listLoading = true;//开启盲等
        let id = row.id
        //发送请求
        this.$http.delete(/dept/+row.id).then(res=> {
          this.listLoading = false;//关闭盲等
          //判断是否删除成功
          if (res.data.success) {
            //弹出提示框
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            //刷新列表
            this.currentPage = 1
            this.getdepts();//刷新列表 成功才会刷新
          } else {
            //删除失败 提示信息
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
        }).catch(() => {//取消要做的事
        });
    },

    employees:[],//存放员工列表的数据
    tree:[], //存放部门树

    //显示编辑界面
    handlesave: function (index, row) {
      this.saveTitle = "编辑"
      if(this.$refs['saveForm']){
        this.$refs['saveForm'].resetFields();//重置表单验证
      }
      this.saveFormVisible = true;//是否显示弹出框
      this.saveForm = Object.assign({}, row);//给表单赋值  要是用克隆
    },
    // //显示新增界面
    handleAdd: function () {
      this.saveTitle = "新增"
      if(this.$refs['saveForm']){
        this.$refs['saveForm'].resetFields();//重置表单验证
      }
      this.saveForm = {
        id:null,
        sn: '',
        name:'',
        state: 1,
        manager_id: null,
        parent_id: null,
      }
      this.saveFormVisible = true;//是否显示弹出框
    },

    //编辑
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {//手动触发验证规则
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {})
              .then(() => {
              this.saveLoading = true;//开启忙等
                //因为双向绑定的原因
                let para = Object.assign({}, this.saveForm);//克隆

                //let para = this.saveForm;//直接赋值

                  if(para.parent_id){
                    if(typeof para.parent_id == "object"){
                      para.parent_id = para.parent_id[para.parent_id.length-1];
                    }
                  }
                 this.$http.put("/dept",para).then(res=>{
                   console.log(res)
                   if(res.data.success){
                     this.saveLoading = false;
                     this.$message({
                       message: res.data.msg,
                       type: 'success'
                     });
                     //重置表单验证
                     this.$refs['saveForm'].resetFields();
                     this.saveFormVisible = false;//关闭模态框
                     this.getdepts();//刷新列表
                   }else{
                     this.$message({
                       message: res.data.msg,
                       type: 'warning'
                     });
                     this.saveLoading = false;
                   }
                 })
            //para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            // savedept(para).then((res) => {
            //   this.saveLoading = false;
            //   //NProgress.done();
            //   this.$message({
            //     message: '提交成功',
            //     type: 'success'
            //   });
            //   this.$refs['saveForm'].resetFields();
            //   this.saveFormVisible = false;
            //   this.getdepts();
            // });
          });
        }
      });
    },


    selsChange: function (sels) {//给多选框绑定事件  如果勾选就获取当前的值
      this.sels = sels;//将选择中的数据赋值给this.sels
    },
    //批量删除
    batchRemove: function () {

      var ids = this.sels.map(item => item.id);//返回一个ids数组  toString 直接把数组变为字符串

      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;//开启忙等
        this.$http.patch("/dept/del",ids).then(res=>{
            this.listLoading = false;
          //判断是否删除成功
          if (res.data.success) {
            //弹出提示框
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            //刷新列表
            this.currentPage = 1
            this.getdepts();//刷新列表 成功才会刷新
          } else {
            //删除失败 提示信息
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
        })
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getdepts();
    this.getEmployee();
    this.getTree();
  }
}
</script>

<style scoped>

</style>